//headers
#include "colorsBack.h"

void printScreen( const gameData *player1, const gameData *player2 );
int parser (gameData *player, gameData *player2);
void winner( gameData *player1, gameData *player2 );
void game( gameData *player1, gameData *player2 );
int menu( gameData * player1, gameData * player2 );
int inintialize( gameData *player1, gameData *player2 );
int loadGame(char *filename, gameData *player1, gameData *player2);
int saveGame(char * filename, gameData * player1, gameData *player2);

int
main(void)
{
	//variables definition
	gameData player[2];
	gameData *player1 = &player[0];
	gameData *player2 = &player[1];
	srand(time(NULL));
	
	if( !menu( player1, player2 ) )
		return SUCCESS;
	if( player1->mode == QUIT )
		return FAILURE;
	
	printScreen( player1, player2 );
	while( playing( player1, player2 ) )
		game(player1, player2);
	winner( player1, player2 );
	
	freeMatrix( player1->dimRow, player1->matrix );
	freeMatrix( player1->dimRow, player1->matrixBack );
	if( player1->mode == MULTIPLAYER )
	{
		freeMatrix( player2->dimRow, player2->matrix );
		freeMatrix( player2->dimRow, player2->matrixBack );
	}
	return SUCCESS;
}

void
game( gameData *player1, gameData *player2 )
{

	
	 int flag;
	switch(player1->turn)
	{
		case 1:
			if( checkSlots( player1 ) )
			{
				do
				{
					printf("Player 1's turn: ");
					flag = parser( player1, player2 );
					if (player1->mode == TIME){
					player1->time = time(NULL);
					}
					printScreen( player1, player2 );
				} while( player1->points != player1->pointsBack || !flag );
			}
		case 2:
			if( checkSlots( player2 ) )
			{
				if( player1->mode == MULTIPLAYER )
				{
					player1->turn = 2;
					player2->turn = 2;
					do
					{
						printf("Player 2's turn: ");
						flag = parser( player2, player1 );
						printScreen( player1, player2 );
					} while( player2->points != player2->pointsBack || !flag);
					player1->turn = 1;
					player2->turn = 1;
				}
			}
	}
	return;
}

void
printScreen( const gameData *player1, const gameData *player2 )
{
	int i, j;

	for( i=0; i<player1->dimRow; i++ )
	{
		printf("%d.\t",i+1);
		for( j=0; j<player1->dimCol; j++ )
			printf("%d ", player1->matrix[i][j] );
		if( player1->mode == MULTIPLAYER )
		{
			printf("\t");
			for( j=0; j<player1->dimCol; j++ )
				printf("%d ", player2->matrix[i][j] );
		}
		printf("\n");
	}
	printf("Player 1's points = %d\n", player1->points );
	if( player1->mode == MULTIPLAYER )
		printf("Player 2's points = %d\n", player2->points );
	if( player1->mode == TIME )
		if( player1->gameTime + player1->iniTime - player1->time <= 0 )
			printf("Time left = 0.\n");
		else
			printf("Time left = %ldm %lds\n", 
			(player1->gameTime + player1->iniTime - player1->time)/H_MIN,
			(player1->gameTime + player1->iniTime - player1->time)%H_MIN);
}


int
parser(gameData *player, gameData *player2)
{
	int c, flag = FAILURE;
	int xStart ,yStart ,xFinish, yFinish;
	char play[MAX_FNAME];
	char *s;
	int point = 0;
	s = play;
	
	scanf("%s" , play);

	if ( strcmp ( "quit" , s ) == 0 )
	{
		exit(SUCCESS);
	}
	else if ( ( strncmp ("save", s , 4) == 0 ) )
	{
		scanf("%s",play);
		if( player->turn == 1 )
			saveGame( s, player, player2 );
		else
			saveGame( s, player2, player );
	}
	else if ( sscanf ( s , "[%d,%d] [%d,%d]", &xStart , &yStart , &xFinish, &yFinish) == 4)
	{
		cpyMatrix( player->matrix, player->matrixBack, player->dimRow, player->dimCol );
		player->pointsBack = player->points;
		if( moveChips (player, xStart-1 , yStart-1 , xFinish-1, yFinish-1 ) )
		{
			if( !(point = points( player, xFinish-1, yFinish-1,
			      player->matrix[xFinish-1][yFinish-1] ) ))
				randomChips( player, player->turnChips );
			flag = SUCCESS;
			player->points += point;
		}
		else
			printf("Can't move\n");
	}
	else if (strcmp ( "undo", s ) == 0 )
		undo( player );
	else printf("Enter a valid option\n");
	
	return flag;
}

int
menu (gameData *player1, gameData *player2)
{

	int principalMenu;
	char fileName[MAX_FNAME];

	do
	{
		principalMenu = getint("Select an option: \n\
1) New Game\n\
2) Load Game \n\
3) Exit \n");
	}
	while ( principalMenu < 1 || principalMenu > 3) ;

	switch(principalMenu)
	{
		case 1:
		do
		{
		player1->mode = getint (" Select Mode :\n\
1) Normal Mode \n\
2) Time Attack \n\
3) Multiplayer \n");
		}while ( player1->mode < 1 || player1->mode > 3);
		break;

		case 2: scanf("%50s", fileName );
			ERASE_BUFFER;
			loadGame(fileName, player1, player2);
		break;

		case 3: player1->mode = QUIT;
		break;
	}
	if ( principalMenu == 1 )
		return initialize( player1, player2 );
	return 1;
}

int
initialize( gameData *player1, gameData *player2 )
{
	player1->dimRow = getint("Amount of rows: ");
	player1->dimCol = getint("Amount of columns: ");
	do
	{
		player1->colors = getint("Color amount: ");
	} while( player1->colors <1 || player1->colors >9 );
	do
	{
		player1->startChips = getint("Starting chips amount: ");
	} while( player1->startChips < 1 || player1->startChips > player1->dimRow*player1->dimCol );
	do
	{
		player1->turnChips = getint("Chips per turn amount: ");
	} while( player1->turnChips < 1 || player1->turnChips > player1->dimRow * player1->dimCol );
	do
	{
		player1->makeLine = getint("Chips to make a line amount: ");
	} while( player1->makeLine < 2 || player1->makeLine > 10);
	player1->points = 0;
	player1->pointsBack = 0;
	player1->turn = 1;
	if( (player1->matrix = newMatrix( player1->dimRow, player1->dimCol )) == NULL )
		return 0;
	if( (player1->matrixBack = newMatrix( player1->dimRow, player1->dimCol )) == NULL )
		return 0;
	randomChips( player1, player1->startChips );
	cpyMatrix( player1->matrix, player1->matrixBack, player1->dimRow, player1->dimCol );
	player1->time = 0;
	player1->iniTime = 0;
	player1->gameTime = 0;
	if( player1->mode == TIME )
	{
		player1->iniTime = time(NULL);
		player1->time = time(NULL);
		player1->gameTime = getint("Time you want to play: ")*60;
	}
	else if( player1->mode == MULTIPLAYER )
	{
		player2->dimRow = player1->dimRow;
		player2->dimCol = player1->dimCol;
		player2->colors = player1->colors;
		player2->startChips = player1->startChips;
		player2->turnChips = player1->turnChips;
		player2->makeLine = player1->makeLine;
		player2->points = 0;
		player2->pointsBack = 0;
		if( (player2->matrix = newMatrix( player2->dimRow, player2->dimCol )) == NULL )
			return 0;
		if( (player2->matrixBack = newMatrix( player2->dimRow, player2->dimCol )) == NULL )
			return 0;
		randomChips( player2, player2->startChips );
		player2->time = 0;
		player2->iniTime = 0;
		player2->gameTime = 0;
	}
	return 1;
}


void
winner( gameData *player1, gameData *player2 )
{
	if( player1->mode == MULTIPLAYER && player1->points != player2->points )
		printf("Player %d wins!!\n", (player1->points > player2->points) ? 1 : 2 );
	else if( player1->mode == MULTIPLAYER && player1->points == player2->points )
		printf("Tie!\n");
	else printf("GAME OVER\n");
	return;
}

int
loadGame(char *filename, gameData *player1, gameData *player2)
{
	FILE *file;
	int i, j;
	file = fopen(filename, "rb");

	if (file == NULL)
	{
		printf("Couldn't open file, verify that such file exists.\n" );
		return FAILURE;
	}

	player1->iniTime = 0;
	player1->time = 0;
	player1->gameTime = 0;
	player1->turn = 1;
	fread(&player1->mode, sizeof(int), 1, file);
	player1->mode++;
	if (player1->mode == TIME)
	{
		fread(&player1->timeLeft, sizeof(int), 1, file);
		player1->iniTime = time(NULL);
		player1->gameTime = player1->timeLeft;
		player1->time =time(NULL); // player1->iniTime + player1->timeLeft;

	}

	else if(player1->mode == MULTIPLAYER)
	{
		fread(&player1->turn, sizeof(int), 1, file);
	}

	fread(&player1->dimRow, sizeof(int), 1, file);
	fread(&player1->dimCol, sizeof(int), 1, file);
	fread(&player1->colors, sizeof(int), 1, file);
	fread(&player1->makeLine, sizeof(int), 1, file);
	fread(&player1->turnChips, sizeof(int), 1, file);
	fread(&player1->points, sizeof(int), 1, file);
	if(!ldMatrix( player1, file ))
		return FAILURE;
	if( (player1->matrixBack = newMatrix( player1->dimRow, player1->dimCol )) == NULL )
		return FAILURE;
	cpyMatrix( player1->matrix, player1->matrixBack, player1->dimRow, player1->dimCol );
	player1->pointsBack = player1->points;
	if( player1->mode == MULTIPLAYER )
	{
		player2->dimRow = player1->dimRow;
		player2->dimCol = player1->dimCol;
		player2->mode= player1->mode;
		fread(&player2->points, sizeof(int), 1, file);
		if(!ldMatrix( player2, file ))
			return FAILURE;
		if( (player2->matrixBack = newMatrix( player2->dimRow, player2->dimCol )) == NULL )
			return FAILURE;

		cpyMatrix( player2->matrix, player2->matrixBack, player2->dimRow, player2->dimCol );
		player2->colors = player1->colors;
		player2->makeLine = player1->makeLine;
		player2->turnChips = player1->turnChips;
		player2->turn = player1->turn;
	}


	printf("Load Succesfull.\n");
	fclose(file);
	return SUCCESS;
}




int
saveGame(char * filename, gameData * player1, gameData *player2)
{
	FILE *file;
	int i, j;
	file = fopen(filename, "wb");
	if (file == NULL)
	{
		fprintf(stderr, "Couldn't open file.\n");
		return FAILURE;
	}
	player1->mode --;
	fwrite(&player1->mode, sizeof(int), 1, file);
	player1->mode++;
	if (player1->mode == MULTIPLAYER){
		fwrite(&player1->turn, sizeof(int), 1 ,file);
	}
	if (player1->mode == TIME){
		player1->timeLeft = (player1->iniTime + player1->gameTime - player1->time);
		fwrite(&player1->timeLeft, sizeof(int) , 1, file);
	}
	
	fwrite(&player1->dimRow, sizeof(int), 1, file);
	fwrite(&player1->dimCol, sizeof(int), 1, file);
	fwrite(&player1->colors, sizeof(int), 1, file);
	fwrite(&player1->makeLine, sizeof(int), 1, file);
	fwrite(&player1->turnChips, sizeof(int), 1, file);
	fwrite(&player1->points, sizeof(int), 1, file);
	svMatrix( player1, file );
	if( player1->mode == MULTIPLAYER )
	{

		fwrite( &player2->points, sizeof(int), 1, file );
		svMatrix( player2, file );
	}

	printf("Game saved\n");
	fclose(file);
	return SUCCESS;
}